package com.example.spingbootvue.controller;

import com.example.spingbootvue.entity.User;
import com.example.spingbootvue.Common.AuthAccess;
import com.example.spingbootvue.mapper.UserMapper;
import com.example.spingbootvue.service.MailService.MailService;
import com.example.spingbootvue.utils.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.example.spingbootvue.service.registerservice;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sendemail")
public class MailController {
    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private registerservice registerservice;

    //发送邮箱验证码
    @AuthAccess
    @GetMapping("/send/{email}")
    public int sendEmail(@PathVariable String email) throws JsonProcessingException {

        //key 邮箱号  value 验证码
        String code = redisTemplate.opsForValue().get(email);

        //从redis获取验证码,可用于在前段判断验证码是否正确
        if (!StringUtils.isEmpty(code)) {
            return 1;
        }
        //如果从redis获取不到，生成新的6位验证码
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过邮箱服务进行发送
        boolean isSend = mailService.sendMail(email, code);
        //生成验证码放到redis里面，设置有效时间为5分钟
        if (isSend) {
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            return 0;
        } else {
            return -1;
        }
    }

    @PostMapping("/register/{usercode}")
    public int registerAll(@RequestBody User user,@PathVariable String usercode){

        int ts=registerservice.register(user,usercode);
        //-2表示邮箱重复
        if(ts==-2){
            return -2;
        }
        else if(ts==-1){
            return -1;
        }else {
            return 1;
        }
    }
}

